package com.rz.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.admin.entity.SysCountry;
import com.rz.admin.mapper.CountryMapper;
import com.rz.admin.service.ICountryService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName CountryServiceImpl
 * @Description 国家/地区service实现类
 * @Author maweiyue
 * @Date 2019/3/26 20:37
 */
@Service
public class SysCountryServiceImpl extends ServiceImpl<CountryMapper, SysCountry> implements ICountryService {

    /**
     * 根据国家代码获取国家信息列表
     * @param code
     * @return
     */
    @Override
    public List<SysCountry> listCountryByCode(String code) {
        QueryWrapper<SysCountry> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("code", code);
        IPage<SysCountry> iPage = new Page<>();
        return page(iPage, queryWrapper).getRecords();
    }

    /**
     * 根据国家代码获取国家信息列表
     * @param name
     * @return
     */
    @Override
    public List<SysCountry> listCountryByName(String name) {
        QueryWrapper<SysCountry> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("c_name", name);
        queryWrapper.or();
        queryWrapper.like("c_fullname", name);
        IPage<SysCountry> iPage = new Page<>();
        return page(iPage, queryWrapper).getRecords();
    }

    /**
     * 根据国家代码获取国家列表
     * @param codeList
     * @return
     */
    @Override
    public List<SysCountry> listCountryByCode(List<String> codeList){
        QueryWrapper<SysCountry> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("code", codeList);
        IPage<SysCountry> iPage = new Page<>();
        return page(iPage, queryWrapper).getRecords();
    }

    /**
     * 获取所有国家列表
     * @return
     */
    @Override
    public List<SysCountry> listAllCountry(){
        QueryWrapper<SysCountry> queryWrapper = new QueryWrapper<>();
        List<SysCountry> sysCountryList = list(queryWrapper);

        return sysCountryList;
    }

    /**
     * 获取所有国家列表，并组成key-value集合，以便页面下拉列表访问
     * @return
     */
    @Override
    public JSONArray selectCountries() {
        List<SysCountry> list = this.listAllCountry();
        JSONArray array = new JSONArray();
        list.forEach(sysCountry -> {
            JSONObject obj = new JSONObject();
            obj.put("value", sysCountry.getCode());
            obj.put("zhName",sysCountry.getcName());
            obj.put("name", sysCountry.getCode() + " " + sysCountry.getcName() + " " + sysCountry.geteName());
            array.add(obj);
        });
        return array;
    }
}
